package com.lft.sort12.other_sort;

import java.util.Arrays;

/**
 * CocktailSort排序【类似冒泡排序，从两头遍历】
 */
public class CocktailSort {
	public static void main(String[] args) {
		int[] a = {2, 6, 3, 5, 1, 4};
		System.out.println(Arrays.toString(cocktailSort1(a)));
	}
	
	public static int[] cocktailSort1(int[] a) {
		for (int i = 0; i < a.length / 2; i++) {
			// 把大的挪到右边
			for (int j = 0; j < a.length - i - 1; j++) {
				if (a[j] > a[j + 1]) {
					swap(a, j, j + 1);
				}
			}
			// 把小的挪到左边
			for (int k = a.length - 1 - (i + 1); k > i; k--) {
				if (a[k] < a[k - 1]) {
					swap(a, k, k - 1);
				}
			}
		}
		return a;
	}
	
	public static int[] cocktailSort2(int[] a) {
		int left = 0, right = a.length - 1;
		while (left < right) {
			for (int i = left; i < right; i++) {
				if (a[i] > a[i + 1]) {
					swap(a, i, i + 1);
				}
			}
			right--;
			for (int i = right; i > left; i--) {
				if (a[i - 1] > a[i]) {
					swap(a, i, i - 1);
				}
			}
			left++;
		}
		return a;
	}
	
	private static int[] swap(int[] a, int i, int j) {
		a[i] = a[i] + a[j];
		a[j] = a[i] - a[j];
		a[i] = a[i] - a[j];
		return a;
	}
}